import requests
import spider
import urllib
from spider import common
import random

class Restaurant():
    def __init__(self):
        self.url = "https://h5.ele.me/restapi/shopping/v3/restaurants"
        self.url_cattegory = "https://h5.ele.me/restapi/shopping/v2/restaurant/category?latitude=22.54286&longitude=114.059563"
        self.param = {
            "limit": "50",
            "latitude": "22.574064",
            "longitude": "113.958347",
            "offset": "0",
            "extras": ["activities","tags"],
            "terminal": "h5",
            "restaurant_category_ids": ["265"]
        }
        self.allCategories = {}
        self.proxies = [
            "176.117.255.182:53100",
            "58.215.140.6:8080",
            "58.210.133.98:58953",
            "182.150.35.89:8080",
            "59.37.33.62:50686"



        ]

    def send(self,url,param=None,headers=None):
        while(True):
            prox = random.sample(self.proxies,1)[0]
            proxies={
                'https': 'https://%s'%prox
            }
            proxies = None;
            try:
                res = requests.get(url,param,headers=headers,proxies=proxies,timeout=10)
                if res.status_code == 200:
                    return res
                else:
                    print("状态码 %s"%str(res.status_code))
            except Exception as e:
                print(e)
            print("准备重连 上次IP是 %s"%prox)


    def run(self):

        self.getType()

        return
        print("开始插入最后的种类信息")
        sql_list = []
        for categorie_key in self.allCategories:
            categorie = self.allCategories.get(categorie_key,[])
            sql = spider.get_insert_sql(categorie,"t_categories")
            sql_list.append(sql)
        spider.excSqls(sql_list)



    def getType(self):
        res = self.send(self.url_cattegory,headers=spider.headers)
        json_data = res.json()
        for type_parent in json_data:
            sub_categories = type_parent.get("sub_categories",None)
            if not sub_categories:
                continue
            container_categorie = {}
            for sub_type in sub_categories:
                name = sub_type.get("name")
                if name == "全部" :
                    continue
                id = sub_type.get("id")
                sub_info = {
                    "id":id,
                    "name":name,
                }
                self.getResturantInfo(sub_info,container_categorie)
                print("类型：%s 插入完成 "%name)


            parent_name = type_parent.get("name")
            print("===================大类型：%s 插入完成 " % parent_name)
            # resturant_count = spider.cursor.execute("select * from t_type a where a.name = '%s'" % str(parent_name))
            # if resturant_count == 1:
            #     ccl = []
            #     for cc in container_categorie:
            #         ccl.append(str(cc))
            #     update_type_categer_sql = "UPDATE t_type SET categories = '%s' WHERE name = '%s'"%("|".join(ccl),parent_name)
            #     print("@@@@@@@@@@@@@准备插入关系数据")
            #     spider.excSql(update_type_categer_sql)

    def getResturantInfo(self,categer,container_categorie):
        id = categer.get("id")
        param =  self.param;
        param["restaurant_category_ids"] = [id]
        res = self.send(self.url,param,headers=spider.headers)
        datas = res.json().get("items");
        result = {}
        for data in datas:
            data = data.get("restaurant")
            image_path = data.get("image_path")
            img_url = common.img_handle_elm(image_path)
            recent =  data.get("recent_order_num");
            if not recent :
                recent = "0"
            resturant_info = {
                "authentic_id":data.get("authentic_id"), #权限？
                "address": data.get("address"),  #地址
                "baidu_id": data.get("baidu_id"), #好像查询物品得到id
                "float_delivery_fee": data.get("float_delivery_fee"), #配送费用
                "float_minimum_order_amount": data.get("float_minimum_order_amount"),  # 多少起送
                "elm_id": data.get("id"), #饿了么的主键吧
                "name": data.get("name"),
                "rating": data.get("rating"), #多少星
                "recent_order_num":recent, #月销量
                "img":img_url+"?imageMogr/format/webp/thumbnail/!130x130r/gravity/Center/crop/130x130/",
            }

            channel_list = []
            flavors = data.get("flavors")

            for flavor in flavors:
                channel = {
                    "resturant_id":resturant_info.get("elm_id"),
                    "categories_id":flavor.get("id")
                }
                channel_list.append(channel)
                categories = {
                    "elm_id":flavor.get("id"),
                     "name":flavor.get("name")
                }
                self.allCategories[flavor.get("id")] = categories
                container_categorie[flavor.get("id")] = categories
             #插入数据库
            self.saveResturant(resturant_info,channel_list)



    def saveResturant(self,resturant_info,channel_list):
        elm_id = resturant_info.get("elm_id")
        resturant_count =  spider.cursor.execute("select * from t_resturant a where a.elm_id = '%s'"%str(elm_id))
        if resturant_count != 0:
            return None;
        sql_list = []
        resturant_sql = spider.get_insert_sql(resturant_info,"t_resturant")
        sql_list.append(resturant_sql)

        for channel in channel_list:
            resturantSql = spider.get_insert_sql(channel, "t_channel_cat2res")
            sql_list.append(resturantSql)

        spider.excSqls(sql_list)